package com.food.chronicles.user.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.food.chronicles.user.entity.Recipe;
import com.food.chronicles.user.service.IRecipeService;
import com.food.chronicles.user.vo.RecipeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URI;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 食谱表 前端控制器
 * </p>
 *
 * @author 牧之
 * @since 2025-05-31
 */
@RestController
@RequestMapping("/recipe")
public class RecipeController {

    @Autowired
    private IRecipeService recipeService;

    @GetMapping("/list")
    public ResponseEntity<Page<RecipeVo>> getRecipes(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer categoryId
    ) {
        // 创建分页参数
        Page<Recipe> pageParam = new Page<>(page, size);

        // 构建查询条件
        LambdaQueryWrapper<Recipe> wrapper = Wrappers.<Recipe>lambdaQuery()
                .like(StringUtils.isNotBlank(keyword), Recipe::getTitle, keyword)
                .eq(categoryId != null, Recipe::getCategory, categoryId)
                .orderByDesc(Recipe::getCreateTime);

        // 执行分页查询
        Page<Recipe> recipePage = recipeService.page(pageParam, wrapper);

        // 转换为VO
        List<RecipeVo> recipeVos = recipePage.getRecords().stream()
                .map(RecipeVo::convertToRecipeVo)
                .collect(Collectors.toList());

        // 创建新的Page对象，保持分页信息
        Page<RecipeVo> voPage = new Page<>(
                recipePage.getCurrent(),
                recipePage.getSize(),
                recipePage.getTotal()
        );
        voPage.setRecords(recipeVos);

        return ResponseEntity.ok(voPage);
    }

    @GetMapping("/{id}")
    public ResponseEntity<Recipe> getRecipeById(@PathVariable Long id) {
        Recipe recipe = recipeService.getById(id);
        if (recipe == null) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.ok(recipe);
    }

    @PostMapping
    public ResponseEntity<Recipe> createRecipe(@RequestBody Recipe recipe) {
        Date date = new Date();
        recipe.setCreateTime(date);
        recipe.setUpdateTime(date);
        boolean result = recipeService.save(recipe);
        if (!result) {
            return ResponseEntity.badRequest().build();
        }
        return ResponseEntity.created(URI.create("/recipe/" + recipe.getId())).body(recipe);
    }

    @PutMapping("/{id}")
    public ResponseEntity<Recipe> updateRecipe(@PathVariable Long id, @RequestBody Recipe recipe) {
        // 检查食谱是否存在
        Recipe existingRecipe = recipeService.getById(id);
        if (existingRecipe == null) {
            return ResponseEntity.notFound().build();
        }

        Date date = new Date();

        // 更新实体ID并设置更新时间
        recipe.setId(id);
        recipe.setUpdateTime(date);

        boolean result = recipeService.updateById(recipe);
        if (!result) {
            return ResponseEntity.badRequest().build();
        }

        return ResponseEntity.ok(recipe);
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteRecipe(@PathVariable Long id) {
        boolean result = recipeService.removeById(id);
        if (!result) {
            return ResponseEntity.notFound().build();
        }
        return ResponseEntity.noContent().build();
    }
}
